import axios from 'axios'

export interface ResponseData<T = any> {
  code: number
  message: string
  data: T
}

const instance = axios.create()

// 请求拦截器
// 设置超时和请求域名
instance.interceptors.request.use(
  config => {
    config.timeout = 10000
    config.baseURL = 'http://localhost:3000'
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  res => {
    return res.data
  },
  err => Promise.reject(err)
)

/**
 * Get请求
 * @param {string} url 请求url地址，不要携带http或https 例：/api/user
 * @param {object} config 请求额外头信息配置 object
 * @returns Promise<any>
 */
export const get = <T>(url: string, config = {}) => instance.get<any, ResponseData<T>>(url, config)

/**
 * Delete请求
 * @param {string} url 请求url地址，不要携带http或https 例：/api/user
 * @param {object} config 请求额外头信息配置 object
 * @returns Promise<any>
 */
export const del = <T>(url: string, config = {}) =>
  instance.delete<any, ResponseData<T>>(url, config)

/**
 * Post请求
 * @param {string} url 请求url地址，不要携带http或https 例：/api/user
 * @param {object|FormData} data 请求体数据
 * @param {object} config 请求额外头信息配置 object
 * @returns Promise<any>
 */
export const post = <T>(url: string, data: any, config = {}) =>
  instance.post<any, ResponseData<T>>(url, data, config)

/**
 * Put请求
 * @param {string} url 请求url地址，不要携带http或https 例：/api/user
 * @param {object|FormData} data 请求体数据
 * @param {object} config 请求额外头信息配置 object
 * @returns Promise<any>
 */
export const put = <T>(url: string, data: any, config = {}) =>
  instance.put<any, ResponseData<T>>(url, data, config)
